<template>
	<view>
		<!-- #ifdef MP-WEIXIN -->
		<view class="ad" v-if="WEBCONFIG.weixin_banner_status && WEBCONFIG.weixin_banner_status == 1">
			<ad :unit-id="WEBCONFIG.weixin_banner_ad_id" ad-theme="white"></ad>
		</view>
		<!-- #endif -->

		<!-- #ifdef MP-TOUTIAO -->
		<view class="ad" v-if="WEBCONFIG.douyin_banner_status && WEBCONFIG.douyin_banner_status == 1">
			<ad :unit-id="WEBCONFIG.douyin_banner_ad_id" ad-theme="white"></ad>
		</view>
		<!-- #endif -->
		<canvas canvas-id="canvasID" id='canvasID' class="vw-100" style="height: 100vw;"
			v-if="canvasImage==''"></canvas>
		<image v-if='image!=""' show-menu-by-longpress='true' class="vw-100" style="height: 100vw;" mode='aspectFit'
			:src="'data:image/jpeg;base64,'+ image" />
		<image v-else :src="canvasImage" class="vw-100" style="height: 100vw;"></image>

		<view class="p-30">
			<view class="content round-8 flex flex-column p-20 text-center grid-gap-8">
				<view class="bg-blue-1 round-6 p-5" v-for="(item,index) in formArr" :key="index">
					<input placeholder="请输入" v-if="item.type==1" v-model='item.text'
						@input="textChange($event,index)" />
					<input v-else placeholder="点击选择成语" disabled @click="open(index)" v-model='item.text' />
				</view>
			</view>
		</view>


		<view class="px-30 ">
			<view class="btn py-10 text-center text-white round-6" v-if='image==""' @click="textCensor()">点击生成</view>
			<view class="btn py-10 text-center text-white round-6" v-else @click="saveAlbum()">点击保存</view>
		</view>




		<uni-popup ref="popup">
			<view class="vw-65 bg-white flex flex-column grid-gap-10 p-30 round-10">
				<view class="flex flex-x-space-between flex-y-center">
					<view class="w-p-20">
						<text class="fs-16 fw-600">姓氏</text>
					</view>
					<view class="round-4 border-hint p-4 w-p-70 box-sizing">
						<input placeholder="请输入姓氏" placeholder-class="fs-12" v-model="popupForm.name" @input='change' />
					</view>
				</view>
				<view class="flex flex-x-space-between flex-y-center">
					<view class="w-p-20 ">
						<text class="fs-16 fw-600">成语</text>
					</view>
					<view class="round-4  box-sizing  w-p-70">
						<uni-data-select v-model="popupForm.idiom" :localdata="idiomList"></uni-data-select>
					</view>
				</view>
				<view @click="sure()" class=" w-p-100 py-10 round-6 text-center text-white btn">确认</view>
			</view>
		</uni-popup>

		<!-- #ifdef MP-WEIXIN -->
		<view v-if="WEBCONFIG.weixin_banner_status && WEBCONFIG.weixin_banner_status == 1">
			<ad :unit-id="WEBCONFIG.weixin_banner_ad_id" ad-theme="white"></ad>
		</view>
		<!-- #endif -->

		<!-- #ifdef MP-TOUTIAO -->
		<view v-if="WEBCONFIG.douyin_banner_status && WEBCONFIG.douyin_banner_status == 1">
			<ad :unit-id="WEBCONFIG.douyin_banner_ad_id" ad-theme="white"></ad>
		</view>
		<!-- #endif -->


	</view>
</template>

<script setup>
	import { ref, getCurrentInstance, nextTick } from 'vue';
	import { useUserStore, useRefs, useWebConfigStore } from '@/stores'
	import { useStorage, $http, $page } from '@/utils/index'
	import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
	import { $interstitialAd, $videoAd } from '@/utils/ad'
	const { USERINFO } = useRefs(useUserStore())
	const { WEBCONFIG } = useRefs(useWebConfigStore())
	const formArr = ref()
	const detail = ref()
	const image = ref('')
	const fIndex = ref(0)
	const popup = ref()
	const idiomList = ref([])
	const canvasImage = ref('')
	const popupForm = ref({
		name: '',
		idiom: ''
	})
	const template_id = ref(0)
	var ctx = null;
	onShareAppMessage(() => {
		let id = USERINFO.value.id || 0
		return {
			title: detail.value.name + ' 姓氏头像',
			path: 'pages/avatar/custom?id=' + detail.value.id + '&template_id=' + template_id.value,
			imageUrl: detail.value.rendering
		}
	})


	onLoad((e) => {
		getDetail(e.id)
		getTemplate(e.template_id)
		template_id.value = e.template_id
		// #ifdef MP-WEIXIN
		if (WEBCONFIG.value?.weixin_interstitial_status == '1') {
			$interstitialAd.init(WEBCONFIG.value?.weixin_interstitial_ad_id)
			$interstitialAd.show()
		}

		if (WEBCONFIG.value?.weixin_incentive_status == '1') {
			$videoAd.init(WEBCONFIG.value?.weixin_incentive_ad_id, (status) => {
				if (status && status.isEnded || status === undefined) {
					addNum(1)
					createImage()
				} else {
					addNum(2)
					uni.showToast({
						title: '抱歉,未观看完无法获得奖励',
						icon: 'none'
					})
				}
			})
		}
		// #endif
		// #ifdef MP-TOUTIAO
		if (WEBCONFIG.value?.douyin_interstitial_status == '1') {
			$interstitialAd.init(WEBCONFIG.value?.douyin_interstitial_ad_id)
			$interstitialAd.show()
		}
		if (WEBCONFIG.value?.douyin_incentive_status == '1') {
			$videoAd.init(WEBCONFIG.value?.douyin_incentive_ad_id, (status) => {

				if (status && status.isEnded || status === undefined) {
					addNum(1)
					createImage()
				} else {
					addNum(2)
					uni.showToast({
						title: '抱歉,未观看完无法获得奖励',
						icon: 'none'
					})
				}
			})
		}
		// #endif
	})
	const textChange = (e, i) => {
		let str = e.detail.value
		if (e.detail.value.length > formArr.value[i]['num']) {
			nextTick(() => {
			formArr.value[i]['text'] = str.substring(0, formArr.value[i]['num'])
			})
		}
		image.value = ''
	}


	const textCensor = () => {
		const showToast = () => {
			uni.showToast({
				title: '请填写完整数据',
				icon: 'none'
			});
			return;
		}
		let str = ''
		let status = true
		for (let i = 0; i < formArr.value.length; i++) {
			if (formArr.value[i].text == '') {
				showToast()
				status = false
				break;
			}
			str = str + formArr.value[i].text
		}
		if (status) {
			$http.get('Avatar/textCensor', { text: str }).then(res => {
				onImage()
			})
		}

	}


	const onImage = () => {

		// #ifdef MP-WEIXIN
		let status = (WEBCONFIG.value.weixin_incentive_status && WEBCONFIG.value.weixin_incentive_status == 1)
		// #endif

		// #ifdef MP-TOUTIAO
		let status = (WEBCONFIG.value.douyin_incentive_status && WEBCONFIG.value.douyin_incentive_status == 1)
		// #endif
		let key = getKey()
		let downloadNum = uni.getStorageSync(key) || 0
		let min_num = uni.getStorageSync('min_num')
		let down = true
		if (+downloadNum >= +min_num) {
			down = false
		}
		if (down == false && status == true) {
			play()
		} else {
			createImage()
		}
	}


	const getTemplate = (id) => {
		$http.get('Template/getDetail', { id: id }).then(res => {
			formArr.value = res.data.content
		})
	}

	const open = (e) => {
		fIndex.value = e
		popup.value.open('center')
	}
	const sure = () => {
		formArr.value[fIndex.value]['text'] = popupForm.value.idiom
		image.value = ''
		popup.value.close()
	}

	const play = () => {
		uni.showModal({
			title: '温馨提示',
			content: '观看广告获得资源',
			success(result) {
				if (result.confirm) {
					$videoAd.show()
				}
			}
		})
	}

	const createImage = () => {
		let queryForm = {
			content: formArr.value,
			id: detail.value.id
		}
		$http.post('Avatar/createImg', queryForm).then(res => {
			image.value = res.data
			addNum(3)
			uni.showModal({
				title: '温馨提示',
				content: '是否保存到本地？',
				success(res) {
					if (res.confirm == true) {
						saveAlbum()
					}
				}
			})
		})

	}

	const addNum = (e) => {
		$http.post('Num/num', { status: e })
	}
	const saveAlbum = () => {
		uni.getSetting({
			success: (res) => {
				// #ifdef MP-WEIXIN
				if (res.authSetting['scope.writePhotosAlbum']) {
					saveImageToPhotosAlbum()
					return
				}
				// #endif

				// #ifdef MP-TOUTIAO
				if (res.authSetting['scope.album'] || res.authSetting['scope.album'] ==
					undefined) {
					saveImageToPhotosAlbum()
					return
				}
				// #endif
				uni.authorize({ //如果没有授权，向用户发起请求
					// #ifdef MP-WEIXIN
					scope: 'scope.writePhotosAlbum',
					// #endif
					// #ifdef MP-TOUTIAO
					scope: 'scope.album',
					// #endif
					success: () => {
						saveImageToPhotosAlbum();
					},
					fail: () => {
						uni.showModal({
							content: '检测到您没打开保存图片的权限，是否去设置打开？',
							confirmText: "确认",
							cancelText: '取消',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting({
										success: (res) => {
											console.log(res);
										}
									})
								} else {
									uni.showToast({
										title: '保存失败',
										icon: 'none'
									})
									return false;
								}
							}
						})
					}
				})
			}
		})
	}



	const saveImageToPhotosAlbum = () => {
		let base64 = image.value
		// #ifdef MP-WEIXIN
		let filePath = wx.env.USER_DATA_PATH
		let fsm = wx.getFileSystemManager()
		// #endif
		// #ifdef MP-TOUTIAO
		let filePath = tt.getEnvInfoSync().common.USER_DATA_PATH
		let fsm = tt.getFileSystemManager()
		// #endif
		filePath = filePath + '/' + Math.random().toString(36).substring(2) + '.png';
		fsm.writeFile({
			filePath: filePath,
			data: base64,
			encoding: 'base64',
			success: res => {
				uni.saveImageToPhotosAlbum({
					filePath: filePath,
					success: function(res2) {
						uni.showToast({
							title: '保存成功'
						})
					},
					fail: function(err) {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
					}
				})
			},
			fail: err => {
				console.log('err', err)
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			}
		})
	}


	const getKey = () => {
		let currentDate = new Date();
		let year = currentDate.getFullYear();
		let month = currentDate.getMonth() + 1; // 注意月份从0开始，需要加1
		let day = currentDate.getDate();
		let key = year + "-" + month + "-" + day
		return key
	}

	const change = (e) => {
		getIdiom(e.detail.value)
	}

	const getDetail = (id) => {
		uni.showLoading({
			title: '获取资源中....'
		})
		$http.get('Avatar/detail', { id: id }).then(res => {
			detail.value = res.data
			init()
		})
	}
	const getIdiom = (e) => {
		if (e == '') {
			return;
		}
		$http.get('Idiom/getList', { key: e }).then(res => {
			idiomList.value = res.data
		})
	}
	const init = () => {
		uni.showLoading({
			title: '获取资源中....'
		})
		ctx = uni.createCanvasContext('canvasID', getCurrentInstance())
		const width = uni.getSystemInfoSync().screenWidth
		uni.getImageInfo({
			src: detail.value.rendering,
			success(res) {
				ctx.drawImage(res.path, 0, 0, width, width)
				ctx.save()
				ctx.setFontSize(14)
				ctx.setFillStyle("rgba(255,255,255,0.5)")
				ctx.setTextBaseline('middle')
				ctx.setTextAlign('center')

				var angle = Math.atan2(width, width);
				ctx.translate(0, width * -1)
				ctx.rotate(angle);
				let row = (Math.ceil(width / 60)) * 2
				console.log(row)
				for (let i = 0; i < row; i++) {
					for (let j = 0; j < row; j++) {
						ctx.fillText('观看视频下载', (i * 100), (j * 60))
					}
				}
				ctx.restore();
				ctx.draw(false,()=>{
					toImage()
				});
				uni.hideLoading()
			}
		})
	}

	const toImage = () => {
		uni.canvasToTempFilePath({
			canvasId: 'canvasID',
			success(res) {
				canvasImage.value = res.tempFilePath
			}
		})
	}
</script>

<style scoped>
	.content {
		border: 2rpx solid #2b85e4;
	}

	.bg-blue-1 {
		background-color: #cde7ff;
	}



	.btn {
		background: linear-gradient(to right, #2979ff, #2b85e4);
	}
</style>